<template>
  <view class="admin-upload-page">
    <view class="page-header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view>
          <text class="header-title">上传壁纸</text>
        </view>
      </view>
    </view>
    
    <view class="upload-form">
      <!-- 壁纸图片上传 -->
      <view class="form-item">
        <text class="label">壁纸图片</text>
        <view class="upload-area" @click="chooseImage" v-if="!wallpaperForm.imageUrl">
          <view class="icon icon-plus" style="font-size: 48px; color: #ccc;">➕</view>
          <text class="upload-text">点击选择壁纸图片</text>
          <text class="upload-hint">支持JPG、PNG格式，建议尺寸1920x1080</text>
        </view>
        <view v-else class="image-preview">
          <image :src="wallpaperForm.imageUrl" mode="aspectFill" class="preview-image"></image>
          <view class="delete-btn" @click.stop="deleteImage">
            <view class="icon icon-close" style="font-size: 18px; color: #fff;">✕</view>
          </view>
        </view>
      </view>
      
      <!-- 壁纸标题 -->
      <view class="form-item">
        <text class="label">壁纸标题</text>
        <input 
          v-model="wallpaperForm.title" 
          type="text" 
          placeholder="请输入壁纸标题" 
          class="form-input"
          maxlength="50"
        />
      </view>
      
      <!-- 壁纸分类 -->
      <view class="form-item">
        <text class="label">壁纸分类</text>
       <picker 
          :range="categories" 
          mode="selector" 
          range-key="name"
          @change="onCategoryChange"
        >
          <view class="category-picker">
            <text>{{ selectedCategory !== '' ? categories[selectedCategory].name : '请选择分类' }}</text>
            <view class="icon icon-arrow-down" style="font-size: 16px; color: #999;">▼</view>
          </view>
        </picker>
      </view>
      
      <!-- 壁纸描述 -->
      <view class="form-item">
        <text class="label">壁纸描述</text>
        <textarea 
          v-model="wallpaperForm.description" 
          placeholder="请输入壁纸描述（可选）" 
          class="form-textarea"
          rows="3"
          maxlength="200"
        ></textarea>
      </view>
      
      <!-- 壁纸标签 -->
      <view class="form-item">
        <text class="label">壁纸标签</text>
        <input 
          v-model="wallpaperForm.tags" 
          type="text" 
          placeholder="多个标签用逗号分隔" 
          class="form-input"
          maxlength="100"
        />
      </view>
      
      <!-- 上传按钮 -->
      <button 
        class="upload-btn" 
        type="primary" 
        :disabled="!canUpload || isUploading"
        @click="uploadWallpaper"
      >
        {{ isUploading ? '上传中...' : '上传壁纸' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive,computed } from 'vue';
import { onLoad} from "@dcloudio/uni-app"

// 状态管理
const selectedCategory = ref('');
const categories = ref([]);
const isUploading = ref(false);
const wallpaperForm = reactive({
	imageUrl:'',
  title: '',
  categoryId: '',
  description: '',
  tags: ''
});

// 计算属性
const canUpload = computed(() => {
  return wallpaperForm.imageUrl && 
         wallpaperForm.title.trim().length > 0 && 
         wallpaperForm.categoryId;
});

// 生命周期
onLoad(() => {
  // 移除管理员权限校验
  loadCategories();
});

// 管理员权限校验已移除

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'admingetCategories'
    });
    
    if (res && res.result && res.result.code === 0) {
      categories.value = res.result.data;
      // 如果有分类，默认选择第一个
      if (categories.value.length > 0) {
        selectedCategory.value = '0';
        wallpaperForm.categoryId = categories.value[0]._id;
      }
    } else {
      // 使用模拟数据
      mockCategories();
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    // 使用模拟数据
    mockCategories();
  }
};

// 模拟分类数据
const mockCategories = () => {
  categories.value = [
    { _id: '1', name: '自然风光', icon: 'landscape' },
    { _id: '2', name: '城市建筑', icon: 'building' },
    { _id: '3', name: '抽象艺术', icon: 'abstract' },
    { _id: '4', name: '动物世界', icon: 'animal' },
    { _id: '5', name: '人文历史', icon: 'history' },
    { _id: '6', name: '游戏动漫', icon: 'game' },
    { _id: '7', name: '科技感', icon: 'tech' },
    { _id: '8', name: '简约风格', icon: 'simple' }
  ];
  // 默认选择第一个分类
  selectedCategory.value = '0';
  wallpaperForm.categoryId = categories.value[0]._id;
};

// 选择图片
// const chooseImage = () => {
//   uni.chooseImage({
//     count: 1,
//     sizeType: ['compressed'],
//     sourceType: ['album', 'camera'],
//     success: (res) => {
//       imageUrl.value = res.tempFilePaths[0];
//     }
//   });
// };
// 选择图片
const chooseImage = async () => {
	// const imageUrls = await Promise.all(
	//   this.images.map(filePath => {
	// 			console.log({filePath});
	//     uniCloud.uploadFile({
	//       filePath:filePath.url,
	// 			 name: 'file',
	//       cloudPath: `moments/${Date.now()}_${Math.random().toString(36).substr(2)}.jpg`
	//     })
			  
	// 		})
	// )
	
	// await uniCloud.callFunction({
	//   name: 'moments',
	//   data: {
	//     action: 'createMoment',
	//     content: this.content,
	// 		  avatar:uni.getStorageSync('userinfo').avatar,
	// 		  avatar_file:uni.getStorageSync('uni-id-pages-userInfo').avatar_file,
	// 		  nickname:uni.getStorageSync('uni-id-pages-userInfo').nickname,
	// 		  openid:uni.getStorageSync('userinfo').wx_openid?uni.getStorageSync('userinfo').wx_openid.mp:'',
	// 		  userId:uni.getStorageSync('uni-id-pages-userInfo')._id,
	//     images: this.images.map(res => res.url),
	// 		  momentStatus:'1'
	//   }
	// })
  try {
    const res = await uni.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed']
    });
    console.log('上传图片',res)
    if (res && res.tempFiles && res.tempFiles.length > 0) {
      const tempFilePath = res.tempFiles[0].tempFilePath;
      // 获取文件扩展名，增加错误处理
      const match = tempFilePath.match(/\.(\w+)$/);
      const extension = match ? match[1] : 'jpg'; // 默认为jpg
      
      // 上传图片到云存储
      const uploadRes = await uniCloud.uploadFile({
        cloudPath: `Wallpaper/${Date.now()}-${Math.random().toString(36).substring(2)}.${extension}`,
        filePath: tempFilePath,
		name: 'file',
      });
      
      if (uploadRes.fileID) {
        wallpaperForm.imageUrl = uploadRes.fileID;
      } else {
        uni.showToast({
          title: '上传图片失败',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('选择图片失败:', error);
  }
};

// 删除图片
const deleteImage = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        wallpaperForm.imageUrl = '';
      }
    }
  });
};

// 分类选择改变
const onCategoryChange = (e) => {
  const index = e.detail.value;
  selectedCategory.value = index;
  wallpaperForm.categoryId = categories.value[index]._id;
};

// 上传壁纸
const uploadWallpaper = async () => {
  if (!canUpload.value || isUploading.value) return;
  
  try {
    isUploading.value = true;
    uni.showLoading({ title: '上传中' });
    
    // 调用云函数保存壁纸信息（使用本地路径作为临时方案）
    const result = await uniCloud.callFunction({
      name: 'adminaddWallpaper',
      data: {
        ...wallpaperForm,
        // imageUrl: imageUrl.value,
        createTime: Date.now(),
        status: 'pending', // 默认为待审核状态
        views: 0,
        downloads: 0,
        favorites: 0
      }
    }).catch(err => {
      console.log('云函数调用失败，使用模拟成功:', err);
      // 模拟成功响应
      return { result: { code: 0, message: '模拟上传成功' } };
    });
    
    uni.hideLoading();
    
    if (result && result.result && result.result.code === 0) {
      uni.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 1500,
        complete: () => {
          setTimeout(() => {
            // 跳转到壁纸列表页
            uni.navigateTo({ url: '/pages/admin/wallpaper-list' });
          }, 1500);
        }
      });
    } else {
      uni.showToast({ 
        title: result.result?.message || '上传失败', 
        icon: 'none' 
      });
    }
    
  } catch (error) {
    console.error('上传壁纸失败:', error);
    uni.hideLoading();
    
    // 即使失败，也模拟成功（方便测试）
    uni.showToast({
      title: '模拟上传成功（测试模式）',
      icon: 'success',
      duration: 1500,
      complete: () => {
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/admin/wallpaper-list' });
        }, 1500);
      }
    });
  } finally {
    isUploading.value = false;
  }
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-upload-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 40rpx;
  
  .page-header {
    display: flex;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .header-left {
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
  }
  
  .upload-form {
    padding: 16px;
    
    .form-item {
      margin-bottom: 20px;
      
      .label {
        display: block;
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
        font-weight: 500;
      }
      
      .form-input {
        width: 100%;
        height: 44px;
        padding: 0 12px;
        background-color: #fff;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        font-size: 14px;
        box-sizing: border-box;
      }
      
      .form-textarea {
        width: 100%;
        padding: 12px;
        background-color: #fff;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        font-size: 14px;
        box-sizing: border-box;
        min-height: 80px;
      }
      
      .upload-area {
        width: 100%;
        height: 200px;
        background-color: #fafafa;
        border: 2px dashed #e8e8e8;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
      }
      
      .upload-area:active {
        background-color: #f0f0f0;
      }
      
      .upload-text {
        font-size: 14px;
        color: #666;
        margin-top: 8px;
      }
      
      .upload-hint {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
      
      .image-preview {
        position: relative;
        width: 100%;
        height: 200px;
        border-radius: 8px;
        overflow: hidden;
        
        .preview-image {
          width: 100%;
          height: 100%;
        }
        
        .delete-btn {
          position: absolute;
          top: 8px;
          right: 8px;
          width: 32px;
          height: 32px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s;
        }
        
        .delete-btn:active {
          background-color: rgba(0, 0, 0, 0.7);
        }
      }
      
      .category-picker {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 44px;
        padding: 0 12px;
        background-color: #fff;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        font-size: 14px;
        box-sizing: border-box;
      }
    }
    
    .upload-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      margin-top: 24px;
      background-color: #007aff;
    }
  }
}
</style>